import { arcgisToGeoJSON, geojsonToArcGIS } from '@esri/arcgis-to-geojson-utils';
import * as shapefile from 'shapefile'; // 使用 shapefile 库
// import shp from 'shpjs'; // 使用 shpjs 库
import shpjs from 'shpjs'
// import {combine, parseShp, parseDbf} from shpjs;//高级api
//例子：combine([parseShp(shpBuffer, /*optional prj str*/),parseDbf(dbfBuffer)]);

// function openShpZip(event) {
//     if (event) {
//         const reader = new FileReader();
//         reader.onload = (e) => {
//             const arrayBuffer = e.target.result;
//             shp(arrayBuffer).then((data) => {
//                 console.log(data); // 输出 Shapefile 文件的数据
//             }).catch((error) => {
//                 console.error(error);
//             });
//         };
//         reader.readAsArrayBuffer(file);
//     }
// };
/** 读取shp的zip */
export async function readShpZip(file) {
    return new Promise(function (resolve, reject) {
      const reader = new FileReader()
      reader.readAsArrayBuffer(file.raw)
      reader.onload = function (e) {
        // const content = e.target.result;
        // const decoder = new TextDecoder('utf-8');
        // const text = decoder.decode(content);
        // console.log(e,text);
        console.log(e.target.result);
        shpjs(this.result).then(res => {
          console.log("zip结果:", res);
          resolve(res)
        }).catch(error => { reject(error) });
      }
    })
  }


export function openShp(file) {
    return new Promise(function (resolve, reject) {
        const reader = new FileReader()
        reader.readAsArrayBuffer(file.raw)
        const featureJson = []
        reader.onload = function (e) {
            //this.result是读取结果,  //此处result是反复读取的
            shapefile.open(this.result).then(source =>
                source.read().then(function log(result) {
                    //console.log('result', result)
                    if (result.done) {
                        if (featureJson.length > 0) {
                            console.log({ message: "文件解析成功", type: 'success' })
                        } else {
                            console.log({ message: "文件解析失败", type: 'error' })
                        }
                        const jsons = {
                            type: "FeatureCollection",
                            features: featureJson,
                            fileName: file.name
                        }
                        console.log('shp结果：', jsons)//有值
                        resolve(jsons);
                        return
                    }
                    if (result.value) { featureJson.push(result.value) }
                    return source.read().then(log)
                }))
                .catch(error => { console.error(error.stack); reject(null); })
        }
    });//promise
}

/**
 * 读取txt：J1	3901410.515	38420747.762		1	
 * @param {文本内容} contents 
 * @returns 
 */
export function toRings(contents) {
    const lines = contents.split("\n")//每行内容
    const rings = []
    let ring = []
    let preNo = 0;//圈号，不为0
    for (let i = 1; i < lines.length; i++) {
        const line = lines[i];
        console.log('line', line)
        if (!line.trim()) { console.log("跳过空白行"); continue; }
        const jzpInfo = line.split("\t");
        if (jzpInfo.length < 4) {
            continue;
        }
        //界址点号，x,y,反算边长，圈号，备注
        // if (jzpInfo.length == 6) {    let jzpId = jzpInfo[0];   let jzpX = jzpInfo[1]; let jzpY = jzpInfo[2];
        //     let jzpLen = jzpInfo[3]; let jzpNo = jzpInfo[4]; let jzpBz = jzpInfo[5]; }
        if (i == 1) {
            preNo = jzpInfo[4] ? jzpInfo[4] : 0;
        }
        if (jzpInfo[4].trim() != preNo) {
            console.log("新环号", jzpInfo, preNo, ring)
            preNo = jzpInfo[4].trim()
            if (ring.length > 0) {
                rings.push(ring)
            }
            ring = [[jzpInfo[2], jzpInfo[1]]]
        } else if (jzpInfo[4]) {
            // console.log("aaa", jzpInfo[2], jzpInfo[1], jzpInfo[4])
            ring.push([jzpInfo[2], jzpInfo[1]])
        }
    }
    rings.push(ring)
    console.log('rings', rings)
    return rings
}

function getRingsBorder(rings) {
    let xmin = rings[0][0][0];
    let xmax = rings[0][0][0];
    let ymin = rings[0][0][1];
    let ymax = rings[0][0][1];
    console.log(xmin, ymin)
    for (let i = 0; i < rings.length; i++) {
        const ring = rings[i];
        //不管有没有环
        for (let j = 0; j < ring.length; j++) {
            const ps = ring[j];
            for (let k = 0; k < ps.length - 1; k++) {
                const p = ps[k];
                if (p[0] < xmin) {
                    xmin = p[0]
                } else if (p[0] > xmax) {
                    xmax = p[0]
                }
                if (p[1] < ymin) {
                    ymin = p[1]
                } else if (p[1] > ymax) {
                    ymax = p[1]
                }
            }
        }
    }
    return { xmin: xmin, ymin: ymin, xmax: xmax, ymax: ymax };
}
